package com.ning.parking.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ning.parking.domain.ParkingLotBaseInfo;
import com.ning.parking.domain.ParkingLotDrivewayInfo;
import com.ning.parking.domain.dto.EditDrivewayDTO;
import com.ning.parking.service.ParkingLotBaseInfoService;
import com.ning.parking.service.ParkingLotDrivewayInfoService;
import com.ning.parking.mapper.ParkingLotDrivewayInfoMapper;
import com.scsonic.common.enums.parklot.DrivewayTypeEnum;
import com.scsonic.common.enums.parklot.ParkingLotConfigStatusEnum;
import com.scsonic.common.mq.topic.Topic;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

/**
 *
 */
@Service
public class ParkingLotDrivewayInfoServiceImpl extends ServiceImpl<ParkingLotDrivewayInfoMapper, ParkingLotDrivewayInfo>
    implements ParkingLotDrivewayInfoService{

    private ParkingLotConfigProcessService parkingLotConfigProcessService;
    private RocketMQProducer mqProducer;
    private ParkingLotBaseInfoService parkingLotBaseInfoService;

    @Override
    public void saveDrvicewayInfo(EditDrivewayDTO dto) {
        List<ParkingLotDrivewayInfo> parkingLotDrivewayInfoEntities = BeanUtil.copyToList(dto.getDrivewayInfoEditDTOList(), ParkingLotDrivewayInfo.class);
        parkingLotDrivewayInfoEntities.forEach(item -> {
            if (item.getDrivewayId() == null) {
                item.setDrivewayCode(getNewDrivewayCode(item.getParkingLotId(),
                        item.getDrivewayType()));
                save(item);

                parkingLotConfigProcessService.saveOrUpdateDrivewayConfig(dto.getParkingLotId(), item.getDrivewayId(), ParkingLotConfigStatusEnum.TO_BE);
            } else {
                updateById(item);
            }
        });
        // 推送通道信息绑定关系到中控网关
        mqProducer.sendAsync(Topic.DRIVEWAY_INFO, selectByParentParkingLotId(dto.getParkingLotId()));
        parkingLotConfigProcessService.saveOrUpdateParkingLotConfig(dto.getParkingLotId(), ConfigStepEnum.DRIVEWAY_INFO_CONFIG, ParkingLotConfigStatusEnum.FINISH);
        //设置该区域配置完成信息
        parkingLotConfigProcessService.saveOrUpdateAreaConfig(dto.getParkingLotId(), ParkingLotConfigStatusEnum.FINISH);
    }

    private ParkingLotBaseInfo selectByParentParkingLotId(Long parkingLotId) {
        return parkingLotBaseInfoService.getById(parkingLotId);
    }

    private String getNewDrivewayCode(Long parkingLotId, DrivewayTypeEnum drivewayType) {
        return parkingLotId+drivewayType.getValue()+UUID.randomUUID().toString();
    }
}




